import os
import urllib
#print '''Content-type: text/html\r\n\r\n'''
edat={} #environment
fdat={} #form data
sdat={} #session data
cdat={} #cookies data

from couchdb import Server


embpy_server = Server('http://20.20.20.56:5984/')
embpy_db = embpy_server['python-tests']

#def db_get(form):

def my_quote(str):
    ret=str.replace('"',"'");
    return ret

for param in os.environ.keys():
    edat[param]=os.environ[param];

def make_ses():
    global fdat,sdat
    if fdat.get("sdat"):
        sdat={}
        _id=fdat.get("sdat");
        if _id:
            sdat=embpy_db.get(_id)
            fdat['sdat_rev']=sdat.get("_rev");
        else:
            fdat['sdat']=''
    if not fdat.get("sdat"):
        sdat['#type']="SES"
        embpy_db.save(sdat)
        fdat['sdat']=sdat.get("_id");
        fdat['sdat_rev']=sdat.get("_rev");


def save_ses():
    global fdat,sdat
#    if sdat.get("_id"):
    sdat['#PAGELOADS']=sdat.get('#PAGELOADS',0)+1
    embpy_db.save(sdat)


def parse_args(args):
    global fdat,sdat
    for p in urllib.unquote_plus(args).split('&'):
        aa=p.split('=')
        if len(aa)>1:
            if fdat.get(aa[0],'') != '':
                fdat[aa[0]]+=";"+my_quote(aa[1])
            else:
                fdat[aa[0]]=my_quote(aa[1])
#check if we have session open.. if not, then open one & push it to couchdb
    make_ses()

#ppkcookie1=testcookie; ppkcookie2=testcookie
def parse_cookies(cooks):
    global cdat
    for p in cooks.split('; '):
        aa=p.split('=')
        if len(aa)>1:
            if cdat.get(aa[0],'') != '':
                cdat[aa[0]]+=";"+my_quote(aa[1])
            else:
                cdat[aa[0]]=my_quote(aa[1])

def dump_cookies():
    global cdat
    global embpy_file,embpy_buffer
    embpy_out("\n<script>\n")
    for c in cdat.keys():
        embpy_out("document.cookie='"+c+"="+cdat[c]+"; expires=Thu, 2 Aug 2011 20:47:11 UTC; path=/'\n")
    embpy_out('</script>\n')
    #change this so that only changes are dumped :)

apu=edat.get('QUERY_STRING','').split('&')
for a in apu:
    b=a.split('=')
    if len(b)>1:
        fdat[b[0]]=b[1];

def embpy_open(fn):
    global embpy_file,embpy_buffer
    embpy_buffer=''
    embpy_file=open(fn,"w")

fdats=[]

def embpy_out(str):
    global embpy_buffer
    fdats.append([len(embpy_buffer),len(embpy_buffer)+len(str)-1,dict.copy(fdat)])
    embpy_buffer+=str

#from BeautifulSoup import BeautifulSoup

def embpy_close():
    global embpy_file,embpy_buffer
    global fdat,sdat
#    apu=embpy_buffer
    dump_cookies()
    apu=embpy_poster(embpy_buffer)
#    soup = BeautifulSoup(apu)
#    embpy_file.write(soup.prettify())

    embpy_file.write(apu)
    if fdat.get('debug',0):
        embpy_file.write("<br><font face=\"courier new\" size=-2 color=red size=-1>fdats:<br>")
        for f in fdats:
            for ff in f:
                embpy_file.write(str(ff)+",")
            embpy_file.write("<br>")
    embpy_file.close()
    save_ses()


taname=""
ta_alku=0
ta_loppu=0
sname=""
options=[]
fixups=[]


def findtxt(home,attr,tag,tago):
    hit=tag.find(attr)
    if hit!=-1:
        return [home+hit,home+hit+len(attr)]
    else:
        return [None,None]

def findval(attr,tag,tago):
    name=tag.find(attr)
#    print attr," >",name
    quoted=0
    if (name !=-1 ):
        lent=len(tag)
        lena=len(attr)
        if tag[name+lena]=='"' or tag[name+lena]=="'":
            p=name+lena+1
            quoted=tag[name+lena];
        else:
            p=name+lena
        for x in range(p,lent):
            if quoted:
                if tag[x]==quoted:
                    return(tago[p:x])
            else:
                if tag[x]==' ':
                    return(tago[p:x])
    return None

def istag(name,tag):
    return(tag[:len(name)]==name)

inform={}

def analyze(home,endi,tag,tago):
    global sname,taname,ta_alku,ta_loppu,options,fixups
    fdatx={}
    for f in fdats:
        if endi>=f[0] and endi<=f[1]:
            fdatx=f[2]
    if istag("INPUT",tag):
        name=findval("NAME=",tag,tago);
        if name:
            inform[name]=1;
            itype=findval("TYPE=",tag,tago);
            if not itype:
                itype='text'
            if itype.upper() == 'RADIO': 
                # radio button .. only on active
                value=findval("VALUE=",tag,tago);
                if value:
                    checked=findtxt(home,"CHECKED",tag,tago);
                    if value==str(fdatx.get(name,'')):
                        #should be checked
                        if checked[0] == None:
                            fixups.append(['INS',[endi,endi], ' checked ','inputti radio]'+name+'['+str(home)+','+str(endi)])
                    else:
                        #should NOT be checked
                        if checked[0] != None:
                            fixups.append(['DEL',[checked[0],checked[1]],"XXXX","inputti radio"])
##########                        
            elif itype.upper() == 'CHECKBOX': 
                # radio button .. only on active
                value=findval("VALUE=",tag,tago);
                if value:
                    checked=findtxt(home,"CHECKED",tag,tago);
                    if str(fdatx.get(name,'')).find(value)!=-1:
                        #should be checked
                        if checked[0] == None:
                            fixups.append(['INS',[endi,endi], ' checked ','inputti checkbox ]'+name+'['+str(home)+','+str(endi)+','+str(fdatx.get(name,''))])
                    else:
                        #should NOT be checked
                        if checked[0] != None:
                            fixups.append(['DEL',[checked[0],checked[1]],"XXXX","inputti checkbox "])

            else:
                value=findval("VALUE=",tag,tago);
                if value == None:
                    print "VALUE PUUTTUU!!!"
                    # select fdats according to buffer position
                    fixups.append(['INS',[endi,endi], ' VALUE="'+my_quote(str(fdatx.get(name,'')))+'" ','inputti ]'+name+'['+str(home)+','+str(endi)+','+itype])
                return ' VALUE="'+str(fdat.get(name,''))+'" '
    if istag("TEXTAREA",tag):
        taname=findval("NAME=",tag,tago);
        if taname:
            inform[taname]=1;
#            print "TEXTAREA NAME='"+taname+"'"
            ta_alku=endi+1
    if istag("/TEXTAREA",tag):
#        print "TEXTAREA NAME='"+taname+"' ****** LOPPU"
#        print "arvo:",fdat.get(taname,"")
        ta_loppu=home
#        print "on:",ta_alku,ta_loppu,'>'+html[ta_alku:ta_loppu]+'<'
        if ta_alku==ta_loppu:  #korvataan vain tyhjat
            print "tyhja"
            # select fdats according to buffer position
            fixups.append(['INS',[ta_alku,ta_alku],fdat.get(taname,"") ,'textarea'])
    if istag("HIDDEN",tag):
        fixups.append(['DEL',[endi-7,endi],"XXXX","hidden"])
        a='';
        for k in fdatx.keys():
            if not inform.get(k,""):
                a+="<INPUT NAME='"+k+"' VALUE='"+fdatx.get(k,'')+"' TYPE=HIDDEN>\n";
        fixups.append(['INS',[endi,endi],a,"hidden"])
    if istag("SELECT",tag):
        sname=findval("NAME=",tag,tago);
        if sname:
            inform[sname]=1;
            print "SLECT NAME='"+sname+"'"
    if sname:
        if istag("OPTION",tag):
            value=findval("VALUE=",tag,tago);
            if value:
                selected=findtxt(home,"SELECTED",tag,tago);
                if selected[0] == None:
                    s=False
                    selected = [endi,endi]
                else:
                    s=True
                print "SLECT NAME='"+sname+"' -> OPTION '"+value+"'"
                options.append([value,s,selected])
                
    if istag("/SELECT",tag):
        print "SLECT NAME='"+sname+"' ****** LOPPU"
        print "arvo:",fdat.get(sname,"")
        print options
        for opt in options:
            # select fdats according to buffer position
            if fdatx.get(sname,"") == opt[0]: #this should be selected
                if opt[1]==False:
                    fixups.append(['INS',opt[2],' SELECTED ',"select"])
                else:
                    pass #ok no changes
            else: #this should be NOT selected
                if opt[1]==True:
                    fixups.append(['DEL',opt[2],"select"])
                else:
                    pass #ok no changes
        sname=''
        
    return None


def embpy_poster(html):
    debug=0
    tag=0
    qmode=0
    addqmode=0
    prev=''
    previ=''
    tagi=''
    tago=''

    global sname,taname,ta_alku,ta_loppu
    htmlout=""
    lenh=len(html)
    for x in range(0,lenh):
        if x+1<lenh:
            next=html[x+1]
        else:
            next=''
        if debug:
            print html[x],':',
        if html[x]=='<' and not qmode:
            start=x
            tag=1
            addqmode=0
            tagi=''
            tago=''
            if debug:
                print "tag start",start,
        if (html[x]=='>' or (html[x]=='/' and next == '>') ) and not qmode:
            if tag==1:
                end=x
                if debug:
                    print "tag end",end,'got: ',html[start:end+1]
                else:
                    print 'tag:',html[start:end+1]," -> ["+tagi[1:]+"]"
                add=analyze(start,end,tagi[1:],tago[1:])
      #          if add:
      #              print "add:",add
      #              htmlout+=add
                tag=0
        if tag:
            if html[x]!=' ' or qmode or prev.isalnum() or prev=='"':
                tagi+=html[x].upper()
                tago+=html[x]
            if (html[x]=='"' or html[x]=="'") and not qmode: 
                # entering qmode
                if debug:
                    print "qmode start",x,
                qmode=html[x]
            elif (html[x]==qmode) and qmode: 
                # leaving qmode
                if debug:
                    print "qmode end",x,
                qmode=0
        if debug:
            print 
        prev=html[x]
#        htmlout+=html[x]
    for x in range(0,lenh):
        dele=0
        for y in fixups:
            if (x == y[1][0] and y[0]=='INS'):
                htmlout+=y[2]
            if (x >= y[1][0] and x <=y[1][1] and y[0]=='DEL'):
                dele=1;
        if not dele:
            htmlout+=html[x]
    if fdat.get('debug',0):
        htmlout+='<br><font face=\"courier new\" size=-2 size=-1>fixups:<br>'
        for f in fixups:
            htmlout+=f[0]+","+str(f[1][0])+","+str(f[1][1])+","+f[2]+","+f[3]+"<br>"

    return(htmlout)


#print 80*"*"
#for f in fixups:
#    print f
#print 80*"*"

#print htmlout
#fo=open("out.html","w")
#fo.write(htmlout)
#fo.close()
